<template>
  <q-dialog class="my_dialog" v-model="isFlagShow">
    <q-card class="my-card q-mx-lg">
      <q-toolbar class="row items-center my_form_header">
        <div>
          {{dlgTitle}}
        </div>
        <q-space />
        <q-btn flat round dense icon="mdi-close" @click="close"/>
      </q-toolbar>
      <q-separator />
      <q-card-setion class="q-mx-sm">
        <q-scroll-area class="my-form-container">
          <div class="col q-gutter-xs">
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>分类名称：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.label"
                  @blur="v$.label.$touch()"
                  :error="v$.label.$error"
                  error-message="请输入不少于2个字符！"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>分类键值：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.value"
                  @blur="v$.value.$touch()"
                  :error="v$.value.$error"
                  error-message="请输入不少于2个字符！"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>图标类型：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="iconTypeArr"
                  v-model="param.graphType"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @blur="v$.graphType.$touch()"
                  :error="v$.graphType.$error"
                  error-message="请选择图形！"
                  @update:model-value="refreshIconType"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>分类图标：</q-item-label>
              <q-item-section>
                <AmyIconSelect
                  :icon-arr="iconArr"
                  :current-icon="param.graphUrl"
                  @update="refreshIcon"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>分类状态：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="statusTypeArr"
                  v-model="param.status"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @blur="v$.status.$touch()"
                  :error="v$.status.$error"
                  error-message="请选择状态！"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>排列序码：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  v-model="param.sortCode"
                  @blur="v$.sortCode.$touch()"
                  :error="v$.sortCode.$error"
                  error-message="请输入不少于2个字符！"
                />
              </q-item-section>
            </q-item>
          </div>
        </q-scroll-area>
      </q-card-setion>
      <q-separator />
      <div class="q-gutter-sm my_form_footer">
        <q-btn
          unelevated
          dense
          label="提交"
          type="submit"
          color="teal-3"
          @click="onSubmit"
          style="width: 80px"
        />
        <q-btn
          unelevated
          dense
          label="重置"
          type="reset"
          color="orange-3"
          @click="onReset"
          style="width: 80px"
        />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, toRefs, PropType, watch, toRef, defineAsyncComponent } from 'vue';
import { isObjectEmpty } from '../../../util/utils';
import { required, numeric, email, minLength } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core';
import { cataItem } from '../../../hook/common/useCatalogType';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';

import { HmiComTypeItem, HmiComTypeItemVO } from './HmiComTypeModel';
import { sysCatalogUrlAPI } from '../../../util/SysBaseConst';
const AmyIconSelect = defineAsyncComponent(() => import('components/basic/AmyIconSelect.vue'));
const AmyImageSelect = defineAsyncComponent(() => import('components/basic/AmyImageSelect.vue'));
import api from 'axios'

export default defineComponent({
  name: 'ComDlg',
  components: {
    AmyIconSelect,
    AmyImageSelect
  },
  props: {
    itemData: {
      type: Object as PropType<HmiComTypeItem>,
      required: true
    },
    iconTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    },
    statusTypeArr: {
      type: Array as PropType<cataItem[]>,
      required: true
    }
  },
  emits: ['submit-component-type', 'cancel-component-type'],
  setup (props, context) {
    //数据解构
    const {
      itemData,
      iconTypeArr,
      statusTypeArr
    } = toRefs(props);

    //*******************************
    //      目录操作
    //*******************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();


    //*******************************
    //      表单项
    //*******************************
    //窗口显示
    let isFlagShow = ref(false);

    //窗口标题
    let dlgTitle = ref('');

    //界面数据
    let param = ref<HmiComTypeItemVO>({
      id: 0,
      label: '',
      value: '',
      graphType: '',
      graphUrl: '',
      status: '',
      sortCode: '',
      description: ''
    });

    //图标类型
    let iconType = ref('请选择图标类型');
    let iconArr = ref<cataItem[]>([]);

    //关闭窗口
    const close = () => {
      isFlagShow.value = false;
      context.emit('cancel-component-type');
    }

    //显示窗口
    const show = (text: string) => {
      isFlagShow.value = true;
      dlgTitle.value = text;
    }

    //提交窗口
    const onSubmit = () => {
      v$.value.$validate();
      if (v$.value.$error) {
        alert('输入参数校验错误!');
      } else {
        isFlagShow.value = false;
        let item: HmiComTypeItem = {
          id: param.value.id,
          label: param.value.label,
          value: param.value.value,
          graphTypeId: findCatalogId(iconTypeArr.value, param.value.graphType),
          graphUrl: param.value.graphUrl,
          statusId: findCatalogId(statusTypeArr.value, param.value.status),
          sortCode: param.value.sortCode,
          description: param.value.description,
          createTime: '',
          createUserId: 0,
          updateTime: '',
          updateUserId: 0
        };

        //发送数据
        context.emit('submit-component-type', item);
      }
    }

    //重置
    const onReset = () => {
      if (param.value) {
        param.value.label = '';
        param.value.value = '';
        param.value.graphType = '';
        param.value.graphUrl = '';
        param.value.status = '';
        param.value.sortCode = '';
        param.value.description = '';
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //更新图标
    const refreshIcon = (icon: string) => {
      param.value.graphUrl = icon;
    }

    //图标类型更新
    const refreshIconType = (sType: string) => {
      let index = (iconTypeArr.value as cataItem[]).findIndex((item) => (item.label === sType));
      if ((iconTypeArr.value) && (index !== -1)) {
        param.value.graphUrl = '';
        api.post(sysCatalogUrlAPI.ICON_SEARCH_LIST_API, {
          id: (iconTypeArr.value[index] as cataItem).id
        }).then((res) => {
          if (res.data.message === 'Success') {
            let list: cataItem[] = res.data.data;
            iconArr.value.length = 0;
            list.forEach((item) => {
              iconArr.value.push(item);
            })
          }
        })
      }
    }

    //*******************************
    //      表单校验
    //*******************************
    //配置校验规则
    const rules = {
      id: {},
      label: { required, minLength: minLength(2) },
      value: { required, minLength: minLength(2) },
      graphType: { required },
      graphUrl: { required },
      status: { required },
      sortCode: { required },
      description: {}
    }

    //使用vuelidate，建立变量对应的校验规则
    const v$ = useVuelidate(rules, {
      id: toRef(param.value, 'id'),
      label: toRef(param.value, 'label'),
      value: toRef(param.value, 'value'),
      graphType: toRef(param.value, 'graphType'),
      graphUrl: toRef(param.value, 'graphUrl'),
      status: toRef(param.value, 'status'),
      sortCode: toRef(param.value, 'sortCode'),
      description: toRef(param.value, 'description')
    });

    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      if (!isObjectEmpty(itemData.value)) {
        param.value.id = itemData.value.id;
        param.value.label = itemData.value.label;
        param.value.value = itemData.value.value;
        param.value.graphUrl = itemData.value.graphUrl;
        param.value.graphType = '请选择图标类型';
        param.value.status = findCatalogLabel(statusTypeArr.value, itemData.value.statusId);
        param.value.sortCode = itemData.value.sortCode;
        param.value.description = itemData.value.description;
      }

      //表单验证初始化
      v$.value.$reset();
    }

    //监听对象的所有属性
    watch(() => itemData, () => {
      init();
    }, { deep: true });

    //启动挂载组件
    onMounted(() => {
      init();
    })

    return {
      itemData,
      iconTypeArr,
      statusTypeArr,

      isFlagShow,
      dlgTitle,
      param,
      iconType,
      iconArr,
      v$,
      init,
      close,
      show,
      onSubmit,
      onReset,
      refreshIcon,
      refreshIconType
    }
  }
})
</script>

<style lang="scss" scoped>
.my-card {
  alignment: center;
  width: 600px;
  max-width: 800px;
  .my-form-container {
    text-align: center;
    padding: 5px 50px 5px 50px;
    height: 450px;
  }
}
</style>
